//
// Created by martin on 2021/5/29.
//

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "fixedthreadpool.h"

/**
 * 用户自定义任务
 * @param arg 任务处理函数参数
 */
void *mytask(void *arg) {
    int d = 0;
    if (arg != NULL) {
        d = *(int *)arg;
    }

    printf("thread %ld is working, input number is %d.\n", pthread_self(), d);
    sleep(1);
    return NULL;
}

/**
 * 客户使用线程池示例
 * @note 创建5个线程的线程池, 运行2 * 20个任务
 */
int main_testpool() {
    int i; /* for循环游标 */
    int jobid; /* 任务id */
    int tasknum = 20; /* 任务数 */
    nFixedThreadPool *pool = NULL;
    /* 创建线程池 */
    fixedthreadpool_create(&pool, 5);

    /* 创建数组num[tasknum] */
    int *num = (int *)malloc(sizeof (int) * tasknum);
    for (i = 0, jobid = 0; i < tasknum; ++i) {
        printf("add job %d to jobs\n", jobid);

        num[i] = jobid++;
        /* 向线程池加入自定义任务及参数 */
        fixedthreadpool_addjob(pool, mytask, &num[i]);
    }

    /* 创建数组anothernum[tasknum] */
    int *anothernum = (int *)malloc(sizeof (int) * tasknum);

    for (i = 0; i < tasknum; ++i) {
        printf("add job %d to jobs\n", tasknum + i);

        anothernum[i] = jobid++;
        /* 向线程池加入自定义任务及参数 */
        fixedthreadpool_addjob(pool, mytask, &anothernum[i]);
    }

    /* 等待所有任务完成 */
    sleep(10);

    /* 销毁线程池 */
    fixedthreadpool_destroy(pool);

    /* 释放数组num[], anothernum[] */
    free(num);
    free(anothernum);

    return 0;
}